package com.imooc.town.aspect;

import com.imooc.town.constant.CookieConstant;
import com.imooc.town.constant.RedisConstant;
import com.imooc.town.exception.SellerAuthorizeException;
import com.imooc.town.utils.CookieUtil;
import com.mysql.jdbc.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * create by song on 2018/3/25
 * To change this template use File | Settings | File Templates.
 */

@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {


    @Autowired
    private RedisTemplate redisTemplate;

    @Pointcut("execution(public * com.imooc.town.controller.seller*.*(..))"+
            "&&!execution(public * com.imooc.town.controller.SellerUserController.*(..))")
    public void verify(){

    }

    @Before ( "verify()" )
    public void doVerify(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes ();
        HttpServletRequest request = attributes.getRequest ();
//        查询cookie
        Cookie cookie = CookieUtil.get ( request, CookieConstant.TOKEN );
        if (cookie == null){
            log.warn("【登录校验】Cookie中查不到token");
            throw new SellerAuthorizeException ();
        }
//        去redis里面查
        String tokenValue = (String) redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isNullOrEmpty (tokenValue)) {
            log.warn("【登录校验】Redis中查不到token");
            throw new SellerAuthorizeException();
        }

    }



}
